package com.begye.smartloan.apptest.huankuan.views

import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.View
import android.widget.RelativeLayout
import com.begye.smartloan.apptest.R
import com.begye.smartloan.apptest.databinding.HuanKuanItemBinding
import com.begye.smartloan.apptest.ext.addBold
import com.begye.smartloan.apptest.ext.addNormal
import org.json.JSONObject

class HuanKuanItem : RelativeLayout {

    private var _binding: HuanKuanItemBinding? = null
    private val binding get() = _binding!!

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : this(
        context,
        attrs,
        defStyleAttr,
        0
    )

    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int,
    ) : super(
        context,
        attrs,
        defStyleAttr,
        defStyleRes
    ) {
        context?.let {
            val layout = View.inflate(it, R.layout.huan_kuan_item, this)
            _binding = HuanKuanItemBinding.bind(layout)
        }
    }

    override fun onFinishInflate() {
        super.onFinishInflate()
        // Ensure binding is not null after inflation
        if (_binding == null) {
            throw IllegalStateException("ViewBinding not initialized for ${javaClass.simpleName}")
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        _binding = null  // Clear the binding reference
    }

    fun initDataSource(value: JSONObject) {
        val showName = value.optString("showName", "")
        val showDetail = value.optString("showDetail", "")
        val title = value.optString("title", "")

        binding.huanKuanItemTitle.text = showName
        binding.huanKuanItemValue.text = showDetail

        if (title == "YES") {
            binding.huanKuanItemTitle.addBold()
            binding.huanKuanItemValue.addBold()

            binding.huanKuanItemTitle.setTextColor(Color.parseColor("#000000"))
            binding.huanKuanItemValue.setTextColor(Color.parseColor("#000000"))
        }else{
            binding.huanKuanItemTitle.addNormal()
            binding.huanKuanItemValue.addNormal()

            binding.huanKuanItemTitle.setTextColor(Color.parseColor("#999999"))
            binding.huanKuanItemValue.setTextColor(Color.parseColor("#999999"))
        }
    }

}